package com.example.speeddating.controller;

import com.example.speeddating.annotaion.LoginUser;
import com.example.speeddating.annotaion.TokenCheck;
import com.example.speeddating.common.BaseResponse;
import com.example.speeddating.common.RespGenerator;
import com.example.speeddating.entity.Photo;
import com.example.speeddating.entity.TokenEntity;
import com.example.speeddating.entity.User;
import com.example.speeddating.enums.ResponseCodeEnum;
import com.example.speeddating.exception.CommonException;
import com.example.speeddating.mapper.UserMapper;
import com.example.speeddating.service.PhotoService;
import com.example.speeddating.service.UserService;
import com.example.speeddating.tool.StringTools;
import com.example.speeddating.tool.WebTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@RestController
@Slf4j
public class ImageUploadController {

    @Autowired
    private PhotoService photoService;

    @Autowired
    private UserService userService;

    @Value("${soulmate.path}")
    private String path;

    @Value("${soulmate.imageBasePath}")
    private String beseUrl;

    @PostMapping("/image/upload/{type}")
    public BaseResponse<String> getImage(@RequestParam("file") MultipartFile file,@PathVariable Integer type) throws IOException {
        if (type==null){
            throw new CommonException("请求参数错误");
        }
        String subPath = "";
        if (type.equals(1)){
            subPath = "topic";
        }

        // 源文件名称
        final String originalFileName = file.getOriginalFilename();
        // 文件后缀
        final String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
        if (!WebTools.IMAGE_EXTENSIONS.contains(suffix)) {
            throw new CommonException("图片格式错误");
        }
        UUID uuid = UUID.randomUUID();
        final String newFileName = uuid + suffix;
        log.info("当前的路径为"+path+subPath+"/"+newFileName);
//        File f = new File(path+subPath + "/" + newFileName);
//        file.transferTo(f);
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path+subPath+"/"+newFileName));
        return RespGenerator.returnOK(subPath+"/"+newFileName);
    }


    @PostMapping("/image/upload")
    public BaseResponse<String> getImage(@RequestParam("file") MultipartFile file,@RequestParam("subPath") String subPath) throws IOException {
        if (subPath==null){
            throw new CommonException("path不能为空");
        }
        // 源文件名称
        final String originalFileName = file.getOriginalFilename();
        // 文件后缀
        final String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
        if (!WebTools.IMAGE_EXTENSIONS.contains(suffix)) {
            throw new CommonException("图片格式错误");
        }
        UUID uuid = UUID.randomUUID();

        final String newFileName = uuid + suffix;
        log.info("当前的路径为"+path+subPath+"/"+newFileName);
//        File f = new File(path+subPath + "/" + newFileName);
//        file.transferTo(f);
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path+subPath+"/"+newFileName));
        return RespGenerator.returnOK(subPath+ "/"+newFileName);
    }


    /**
     * 删除图片
     * @param jsonString
     * @return
     * @throws IOException
     */
    @DeleteMapping("/image/delete")
    public BaseResponse<String> deleteImage(@RequestBody HashMap<String,Object> jsonString) throws IOException {
        if (jsonString.get("url")==null){
            throw new CommonException("url不能为空");
        }
//        分割
        String path = jsonString.get("url").toString();
        String[] parts = path.split("image/");  // 根据 "image/" 进行分隔
        String fileName = "";
        if (parts.length > 1) {
            fileName = this.path + parts[1].replace("/","\\");  // 获取第二部分
            File file = new File(fileName);
            if(!file.exists()){
                throw new CommonException("图片不存在");
            }else{
                //判断这是不是一个文件，ps：有可能是文件夹
                if(file.isFile()){
                    file.delete();
                }
            }
            return RespGenerator.returnOK("删除成功");
        } else {
           log.info("path格式不正确");
            return RespGenerator.returnOK("删除成功");
        }
    }


    /**
     * 删除照片墙
     * @param jsonString
     * @return
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    @TokenCheck(roles = "user")
    @DeleteMapping("/user/photo/del")
    public BaseResponse deletePhoto(@LoginUser TokenEntity tokenEntity, @RequestBody HashMap<String,Object> jsonString) throws IOException {
        if (jsonString.get("url")==null||jsonString.get("index")==null){
            throw new CommonException(ResponseCodeEnum.CODE_600);
        }
        int index = Integer.parseInt(jsonString.get("index").toString());
        Photo firstPhoto = photoService.getFirstPhotoByUserId(tokenEntity.getId());
        if (index==0&&firstPhoto!=null){  //修改头像地址 删除第一个photo
            User user = new User();
            user.setId(tokenEntity.getId());
            user.setAvator(firstPhoto.getUrl());
            userService.updateUser(user);
            photoService.deletePhoto(firstPhoto.getId());
        }
        if (jsonString.get("id")!=null&&index!=0){
            photoService.deletePhoto(Long.valueOf(jsonString.get("id").toString()));
        }
        return this.deleteImage(jsonString);
    }


}